package dao

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"serve/shared/id"
	mgutil "serve/shared/mongo"
	"serve/shared/mongo/objid"
)

const openIDField = "open_id"

type Mongo struct {
	col *mongo.Collection
}

func NewMongo(db *mongo.Database) *Mongo {
	return &Mongo{
		col: db.Collection("account"),
	}
}

//ResolveAccountID 根据openid 获取id
func (m *Mongo) ResolveAccountID(c context.Context, openID string) (id.AccountID, error) {

	insertId := mgutil.NewObjID() // 生成一个id

	res := m.col.FindOneAndUpdate(c, bson.M{
		openIDField: openID,
	},
		mgutil.SetOnInsert(bson.M{
			mgutil.IDFieldName: insertId,
			openIDField:        openID,
		}),
		options.FindOneAndUpdate().
			SetUpsert(true).
			SetReturnDocument(options.After))

	if err := res.Err(); err != nil {
		return "", fmt.Errorf("cannot FindOneAndUpdate:%v", err)
	}

	var row mgutil.ObjIDField

	err := res.Decode(&row)
	if err != nil {
		return "", fmt.Errorf("cannot res.Decode:%v", err)
	}

	return objid.ToAccountId(row.ID), nil
}
